package com.itheima.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.BlogMapper;
import com.itheima.dao.BlogSortMapper;
import com.itheima.entity.PageResult;
import com.itheima.pojo.BlogSort;
import com.itheima.service.BlogSortService;
import com.itheima.utils.DateUtils;
import org.omg.CORBA.OBJ_ADAPTER;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class BlogSortServiceImpl implements BlogSortService {
    @Autowired
    private BlogSortMapper blogSortMapper;

    @Autowired
    private BlogMapper blogMapper;

    @Override
    @Transactional
    public void add(Map<String,Object> blogSortVO) {
        String uid = (String) blogSortVO.get("uid");
        BlogSort blogSort1 = blogSortMapper.selectByPrimaryKey(uid);
        if(blogSort1 != null){
            throw new RuntimeException("uid已存在");
        }
        //存入条件
        BlogSort blogSort = new BlogSort();
        if(blogSortVO != null){
            //取出数据
            String content = (String) blogSortVO.get("content");
            System.out.println((blogSortVO.get("sort")) instanceof Integer);
//            Long sort = ((Integer) blogSortV0.get("sort")).longValue(); //java.lang.String cannot be cast to java.lang.Integer
            Long sort = Long.parseLong((String) blogSortVO.get("sort"));//java.lang.Integer cannot be cast to java.lang.String

            String sortName = (String) blogSortVO.get("sortName");
            Integer status = Integer.parseInt((String) blogSortVO.get("status")) ;
            Date date = new Date();

            if(uid != null){
                blogSort.setUid(uid);
            }
            if(content != null){
                blogSort.setContent(content);
            }
            if(sort != null){
                blogSort.setSort(sort);
            }
            if(sortName != null){
                blogSort.setSortName(sortName);
            }
            if(status != null){
                blogSort.setStatus(status);
            }
            blogSort.setCreateTime(date);
            blogSort.setUpdateTime(date);

        }
        blogSortMapper.insert(blogSort);
    }

    @Override
    public List<Map<String,Object>> blogSortByCite() {
        List<Map<String,Object>> resultList = new ArrayList<>();
        List<Map<String,Object>> blogSorts = blogSortMapper.blogSortByCite();
        if(blogSorts == null){
            throw new RuntimeException("网络波动，查询出错");
        }
        Long maxSort = blogSortMapper.selectMaxSort();
        for (int i = blogSorts.size()-1; i >= 0; i--) {
            Map<String, Object> blogSortMap = blogSorts.get(i);
            String uid = (String) blogSortMap.get("uid");
            BlogSort blogSort = blogSortMapper.selectByPrimaryKey(uid);
            maxSort = maxSort + 1;
            blogSort.setSort(maxSort);
            blogSortMapper.updateByPrimaryKeySelective(blogSort);
            blogSort = this.getBlogSortFromDB(blogSortMap);
            Map<String,Object> map = new HashMap<>();
            map.put("blogSort",blogSort); //blogSort数据
            map.put("count",blogSortMap.get("count(1)")); //引用数量
            resultList.add(map);
        }
        return resultList;
    }

    @Override
    public List<BlogSort> blogSortByClickCount() {
        Example example = new Example(BlogSort.class);
        example.setOrderByClause("click_count DESC");
        List<BlogSort> blogSorts = blogSortMapper.selectByExample(example);
        return blogSorts;
    }

    //根据blogSortUid删除数据
    @Override
    @Transactional
    public int deleteBatch(List<Map<String,Object>> blogSortVoList) {
        int i = 0;
        if(blogSortVoList != null){
            for (Map<String, Object> map : blogSortVoList) {
                if(map != null){
                    String uid =  map.get("uid").toString();
                    i = blogSortMapper.deleteByPrimaryKey(uid);
                }
            }
        }
        return i;
    }

    @Override
    public void edit(Map<String,Object> blogSortVo) {
        String uid = (String) blogSortVo.get("uid");
        if(uid == null){
            throw new RuntimeException("uid不存在");
        }
        if(uid.length() != 32){
            throw new RuntimeException("uid length must be 32");
        }
        String s = JSON.toJSONString(blogSortVo);
        BlogSort blogSort = JSON.parseObject(s, BlogSort.class);
        blogSortMapper.updateByPrimaryKeySelective(blogSort);
    }

    @Override
    public PageResult<BlogSort> getList(Map<String, Object> blogSortV0) {
        int currentPage = (int) blogSortV0.get("currentPage");
        int pageSize = (int) blogSortV0.get("pageSize");
        PageHelper.startPage(currentPage,pageSize);
        BlogSort blogSort = JSON.parseObject(JSON.toJSONString(blogSortV0), BlogSort.class);
        PageResult<BlogSort> blogSortPageResult = new PageResult<>();
        Page<BlogSort> blogSorts = (Page<BlogSort>) blogSortMapper.select(blogSort);
        blogSortPageResult.setRecords(blogSorts);
        blogSortPageResult.setOptimizeCountSql(true);
        blogSortPageResult.setSearchCount(true);
        blogSortPageResult.setSize(blogSorts.getTotal());
        blogSortPageResult.setCurrent((long)blogSorts.getPageNum());


        return blogSortPageResult;
    }

    @Override
    public void stick(Map<String, Object> blogSortV0) {
        Long maxSortFound = blogSortMapper.selectMaxSort();
        String uid = (String) blogSortV0.get("uid");
        if(uid != null){
            BlogSort blogSort = blogSortMapper.selectByPrimaryKey(uid);
            Long sort = blogSort.getSort();
            if(sort >= maxSortFound){
                throw new RuntimeException("当前项已处于置顶位置！");
            }
            sort = maxSortFound + 1;
            blogSort.setSort(sort);
            blogSortMapper.updateByPrimaryKeySelective(blogSort);
        } else {
            throw new RuntimeException("无uid传入");
        }
    }

    @Override
    public List<String> getArticleByMonth(String monthDate) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月");
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM");
        try {
            Date date = sdf.parse(monthDate);
            String format = sdf1.format(date);
            format = format + "%";
            return blogSortMapper.getArticleByMonth(format);
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    }


    @Override
    public List<String> getSortList() {
        List<String> sortTimeList = blogSortMapper.getSortList();
        List<String> YMList = new ArrayList<>();
        if(sortTimeList == null){
            throw new RuntimeException("无月份数据");
        }
        for (String sortTime : sortTimeList) {
            System.out.println(sortTime);
            String year = sortTime.substring(0, 4);
            String month = sortTime.substring(4);
            String date = year + "年" + month + "月";
            YMList.add(date);
        }
        return YMList;

    }

    @Override
    public List<BlogSort> getBlogSortList() {
        return blogSortMapper.selectAll();
        //TransientDataAccessResourceException: Error attempting to get column 'create_time' from result set.  Cause: java.sql.SQLException: Value '0000-00-00 00:00:00' can not be represented as java.sql.Timestamp
    }


    //从map中取出数据并封装到blogSort中
    private BlogSort getBlogSort(Map<String,Object> blogSortV0){
        if(blogSortV0 != null){
            //取出数据
            String content = (String) blogSortV0.get("content");
            System.out.println((blogSortV0.get("sort")) instanceof Integer);
//            Long sort = ((Integer) blogSortV0.get("sort")).longValue(); //java.lang.String cannot be cast to java.lang.Integer
            Long sort = Long.parseLong((String) blogSortV0.get("sort"));//java.lang.Integer cannot be cast to java.lang.String

            String sortName = (String) blogSortV0.get("sortName");
            Integer status = (Integer)(blogSortV0.get("status")) ;
            String uid = (String) blogSortV0.get("uid");
            Date date = new Date();
            //存入条件
            BlogSort blogSort = new BlogSort();
            if(uid != null){
                blogSort.setUid(uid);
            }
            if(content != null){
                blogSort.setContent(content);
            }
            if(sort != null){
                blogSort.setSort(sort);
            }
            if(sortName != null){
                blogSort.setSortName(sortName);
            }
            if(status != null){
               blogSort.setStatus(status);
            }
            blogSort.setCreateTime(date);
            blogSort.setUpdateTime(date);

            return blogSort;
        } else {
            return null;
        }
    }

    //从数据库取出数据并封装到blogSort中
    private BlogSort getBlogSortFromDB(Map<String,Object> blogSortV0){
        if(blogSortV0 != null){
            //取出数据
            String content = (String) blogSortV0.get("content");
            Long sort = ((Integer)blogSortV0.get("sort")).longValue();
            String sortName = (String) blogSortV0.get("sortName");
            Boolean status = (Boolean) blogSortV0.get("status");
            String uid = (String) blogSortV0.get("uid");
            Date date = new Date();
            //存入条件
            BlogSort blogSort = new BlogSort();
            if(uid != null){
                blogSort.setUid(uid);
            }
            if(content != null){
                blogSort.setContent(content);
            }
            if(sort != null){
                blogSort.setSort(sort);
            }
            if(sortName != null){
                blogSort.setSortName(sortName);
            }
            if(status){
                blogSort.setStatus(1);
            } else {
                blogSort.setStatus(0);
            }
            blogSort.setCreateTime(date);
            blogSort.setUpdateTime(date);

            return blogSort;
        } else {
            return null;
        }
    }

}
